using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Gif.Components;
using System.Linq;

namespace Example
{
    class ExampleMain
    {
        [STAThread]
        static void Main(string[] args)
        {
            /* create Gif */
            //you should replace filepath
            string[] imageFilePaths = Directory.GetFiles("../../res/");
        
            string outputPath = Path.GetDirectoryName(imageFilePaths[0]);
            string outGifFile = Path.Combine(outputPath, "test.gif");


            AnimatedGifEncoder e = new AnimatedGifEncoder();
            e.Start(outGifFile);
            e.SetDelay(500);
            //-1:no repeat,0:always repeat
            e.SetRepeat(0);

            int res;
            imageFilePaths = imageFilePaths.Where(t => int.TryParse(Path.GetFileNameWithoutExtension(t), out res)).ToArray();

            for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            {
                e.AddFrame(Image.FromFile(imageFilePaths[i]));
            }
            e.Finish();
            /* extract Gif */
         

            GifDecoder gifDecoder = new GifDecoder();
            gifDecoder.Read(outGifFile);
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);  // frame i
                frame.Save(Path.Combine(outputPath, Guid.NewGuid().ToString() + ".png"), ImageFormat.Png);
            }
        }
    }
}
